#!/bin/bash
# 
# This script is used internally by other scripts, 
# it is not intended to be used like this.
#
# this script was originally downloaded from:
# http://jeroen.a-eskwadraat.nl/sw/annotate 
#
# This file is part of ATS (Automated Testing System), 
# http://http://wiki.mandriva.com/en/Automated_testing_system
#
# Executes a program annotating the output linewise with time and stream
# Version 1.2
#
# Copyright 2003, 2004 Jeroen van Wolffelaar <jeroen@wolffelaar.nl>
# Copyright 2009 Mandriva <http://www.mandriva.com>
# Copyright 2009 Jean-Dominique Frattini <jd.frattini@free.fr>
#
# $Id $
#
# ATS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# ATS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pulse 2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

addtime ()
{
   while read line; do
      echo "`date +%H:%M:%S` $1: $line"
   done

   # the following is important just because some binaries don't close stdout
   # or stderr FD or don't put \n on the last string output so the last
   # line couldn't be get otherwise.

#   echo "If what's following is not empty it then means the program has not "
#   echo "correctly flushed/closed stdout/stderr: \"$line\""
}

OUT=`mktemp /tmp/annotate.XXXXXX` || exit 1
ERR=`mktemp /tmp/annotate.XXXXXX` || exit 1

rm -f $OUT $ERR
mkfifo $OUT $ERR || exit 1

addtime OUT < $OUT &
addtime ERR < $ERR &

echo "`date +%H:%M:%S` IN: Started $@"
"$@" > $OUT 2> $ERR ; EXIT=$?
rm -f $OUT $ERR
wait

echo "`date +%H:%M:%S` IN: Finished with exitcode $EXIT"

exit $EXIT

